/** ServerManager */
package postpic.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

/**
 * ServerManager accepts incoming connection requests and delegates threads to
 * handle individual socket connections.
 */
public class ServerManager extends Thread {
	private static final Logger LOGGER = Logger.getLogger(ServerManager.class.getName());

	private int port = 443;
	
	/**
	 * Runs the ServerManager thread.
	 */
	public void run() {
		try {
			//Starts the non-blocking server on the set port 
			ServerSocketChannel server = ServerSocketChannel.open();
			server.socket().bind(new InetSocketAddress(port));
			server.configureBlocking(false);
			
			System.out.println("Server is now running on port " + port);
			
			//Loop indefinitely, accepting connections as they come
			for (;;) {
				
				//Accept a new channel when a client connects
				SocketChannel channel = server.accept();
				
				if (channel != null) {
					LOGGER.info("Connection made.");
					
					//Get the associated socket and manage it
					Socket sock = channel.socket();
					sock.setKeepAlive(true);
					Thread thr = new Thread(new SocketManager(sock));
					thr.start();
					LOGGER.info("Set up thread for new connection.");
				}
			}
		} catch (IOException ex) {
			LOGGER.warning("Error running ServerManager!" + ex.getMessage());
		}
	}
	
	/**
	 * The main method for the server.
	 * @param args command-line arguments
	 */
	public static void main(String[] args) {
		//Create a new thread to run the ServerManager
		Thread serverThread = new ServerManager();
		serverThread.start();
	}
}
